#!/bin/bash
CPRO=/opt/cprocsp/bin/amd64
USER=$(who | awk '{print $1}' | head -n1)
mkdir -p /tmp/autocert

log()
{
	echo $1
	echo $1 >> /var/log/autocert.log
}

log "Начало лога - $(date +'%d.%m.%Y %T')"
log "Пользователь: $USER"
log "Поиск контейнеров..."
sleep 3
MATCHED=$(sudo -u $USER $CPRO/csptest -keyset -enum_cont -verifycontext -uniq | grep -o '|.*' | cut -d '|' -f2)

if [ -z "$MATCHED" ]; then
	exit 1
fi

log "Обнаружены $MATCHED"

install_root()
{
	wget -nc -nv --tries=3 --timeout=3 $1 --directory /tmp/autocert
	if [[ "$?" != 0 ]]; then
		log "Не удалось скачать $1";
		log "Использую прокси s4.okb3.local:3665"
		wget -nv $1 -e use_proxy=yes -e http_proxy=s4.okb3.local:3665 --tries=3 --timeout=3 --directory /tmp/autocert;
		if [[ "$?" != 0 ]]; then
			log "Не удалось скачать $1"
			exit 1
		fi
	fi
	$CPRO/certmgr -inst -store mroot -file /tmp/autocert/$(basename $1)
}

for CONTAINER in $MATCHED
do
	if ! $CPRO/certmgr -list -cont $CONTAINER | grep "OGRN=1027402332770"; then
		log "Игнорирую физ.лицо $CONTAINER"
		continue;
	fi
	log "Установка контейнера $CONTAINER в хранилище пользователя $USER"
	sudo -u $USER $CPRO/certmgr -inst -cont $CONTAINER
	CERTIFICATE=$(sudo -u $USER $CPRO/certmgr -list -cont $CONTAINER | grep -E -o -m 1 'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*).crt')
	while true
	do
		log "Установка корневого сертификата $CERTIFICATE"
		CERTIFICATE=$(install_root $CERTIFICATE | grep -E -o -m 1 'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*).crt')
		if [[ "$?" != 0 ]]; then
			break;
		fi
	done
done
log "Конец лога"
echo >> /var/log/autocert.log
